package com.example.earthquake.provider;

import java.util.HashMap;

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;

public class EarthquakeProvider extends ContentProvider {
	
	public static final Uri CONTENT_URI = Uri.parse("content://com.example.earthquake.provider/earthquakes");
	
	public static final String KEY_ID = "_id";
	public static final String KEY_DATE = "date";
	public static final String KEY_DETAILS = "details";
	public static final String KEY_SUMMARY = "summary";
	public static final String KEY_LOCATION_LAT = "latitude";
	public static final String KEY_LOCATION_LNG = "longitude";
	public static final String KEY_MAGNITUDE = "magnitude";
	public static final String KEY_LINK = "link";
	
	private EarthquakeDatabaseHelper myDbHelper;
	
	private static final int QUAKES = 1;
	private static final int QUAKE_ID = 2;
	private static final int SEARCH = 3;
	private static final UriMatcher matcher;
	
	private static final HashMap<String, String> SEARCH_PROJECTION_MAP;
	
	static {
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI("com.example.earthquake.provider", "earthquakes", QUAKES);
		matcher.addURI("com.example.earthquake.provider", "earthquakes/#", QUAKE_ID);
		matcher.addURI("com.example.earthquake.provider", SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH);
		matcher.addURI("com.example.earthquake.provider", SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
		matcher.addURI("com.example.earthquake.provider", SearchManager.SUGGEST_URI_PATH_SHORTCUT, SEARCH);
		matcher.addURI("com.example.earthquake.provider", SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", SEARCH);
		
		SEARCH_PROJECTION_MAP = new HashMap<String, String>();
		SEARCH_PROJECTION_MAP.put(SearchManager.SUGGEST_COLUMN_TEXT_1, KEY_SUMMARY + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_1);
		SEARCH_PROJECTION_MAP.put("_id", KEY_ID + " AS " + "_id");
	}

	@Override
	public boolean onCreate() {
		myDbHelper = new EarthquakeDatabaseHelper(getContext(), EarthquakeDatabaseHelper.DATABASE_NAME, null, EarthquakeDatabaseHelper.DATABASE_VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = myDbHelper.getWritableDatabase();
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		builder.setTables(EarthquakeDatabaseHelper.DATABASE_TABLE);
		
		switch (matcher.match(uri)) {
		case QUAKE_ID:
			String id = uri.getPathSegments().get(1);
			builder.appendWhere(KEY_ID + "=" + id);
			break;
			
		case SEARCH:
			builder.appendWhere(KEY_SUMMARY + " LIKE \"%" + uri.getPathSegments().get(1) + "%\"");
			builder.setProjectionMap(SEARCH_PROJECTION_MAP);
			break;

		default:
			break;
		}
		String orderBy;
		if(sortOrder == null) {
			orderBy = KEY_DATE;
		} else {
			orderBy = sortOrder;
		}
		
		Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, orderBy);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public String getType(Uri uri) {
		switch (matcher.match(uri)) {
		case QUAKE_ID:
			return "vnd.android.cursor.item/vnd.example.earthquake";

		case QUAKES:
			return "vnd.android.cursor.dir/vnd.example.earthquake";
			
		case SEARCH:
			return SearchManager.SUGGEST_MIME_TYPE;

		default:
			throw new IllegalArgumentException("Unsupported URI:" + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = myDbHelper.getWritableDatabase();
		long id = db.insert(EarthquakeDatabaseHelper.DATABASE_TABLE, null, values);
		
		if(id > -1) {
			Uri newUri = ContentUris.withAppendedId(CONTENT_URI, id);
			getContext().getContentResolver().notifyChange(newUri, null);
			return newUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = myDbHelper.getWritableDatabase();
		
		int count;
		switch (matcher.match(uri)) {
		case QUAKES:
			count = db.delete(EarthquakeDatabaseHelper.DATABASE_TABLE, selection, selectionArgs);
			break;
			
		case QUAKE_ID:
			String id = uri.getPathSegments().get(1);
			count = db.delete(EarthquakeDatabaseHelper.DATABASE_TABLE, 
					KEY_ID + "=" + id + (!TextUtils.isEmpty(selection) ? " and (" + selection + ')' : ""), selectionArgs);

		default:
			throw new IllegalArgumentException("Unsupported URI:" + uri);
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
SQLiteDatabase db = myDbHelper.getWritableDatabase();
		
		int count;
		switch (matcher.match(uri)) {
		case QUAKES:
			count = db.update(EarthquakeDatabaseHelper.DATABASE_TABLE, values, selection, selectionArgs);
			break;
			
		case QUAKE_ID:
			String id = uri.getPathSegments().get(1);
			count = db.update(EarthquakeDatabaseHelper.DATABASE_TABLE, values,
					KEY_ID + "=" + id + (!TextUtils.isEmpty(selection) ? " and (" + selection + ')' : ""), selectionArgs);

		default:
			throw new IllegalArgumentException("Unsupported URI:" + uri);
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		
		return count;
	}
	
	private static class EarthquakeDatabaseHelper extends SQLiteOpenHelper {
		
		private static final String DATABASE_NAME = "earthquakes.db";
		private static final int DATABASE_VERSION = 1;
		private static final String DATABASE_TABLE = "earthquakes";
		
		private static final String DATABASE_CREATE = 
				"create table " + DATABASE_TABLE + " ("
				+ KEY_ID + " integer primary key autoincrement, "
				+ KEY_DATE + " integer, "
				+ KEY_DETAILS + " text, "
				+ KEY_SUMMARY + " text, " 
				+ KEY_LOCATION_LAT + " float, "
				+ KEY_LOCATION_LNG + " float, "
				+ KEY_MAGNITUDE + " float, "
				+ KEY_LINK + " text);";

		public EarthquakeDatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop table if exists " + DATABASE_TABLE);
			onCreate(db);
		}
		
	}

}
